package com.budwk.app.base.utils;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.budwk.app.miniapp.common.CommonConstants;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StrUtil {

    private static final Pattern linePattern = Pattern.compile("_(\\w)");

    // 生成雪花算法id
    public static String getSnowId() {
        SnowflakeGenerator snowflakeGenerator = new SnowflakeGenerator();
        Long next = snowflakeGenerator.next();
        return String.valueOf(next);
    }
    // 如果为空 返回-
    public static String formatStr(String str) {
        if (StringUtils.isEmpty(str)) {
            return CommonConstants.HORIAONTAL;
        }
        return str;
    }

    /**
     * 下划线转驼峰
     * @param str 字符串
     * @return 转换后的字符串
     */
    public static String lineToHump(String str) {
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 处理所有的字符串空格情况
     * @param obj
     */
    public static void handleStrTrim(Object obj) {
        for (Field field : obj.getClass().getDeclaredFields()) {
            try {
                field.setAccessible(true);
                if ("java.lang.String".equals(field.getType().getName())) {
                    String value = (String) field.get(obj);
                    if (value != null) {
                        field.set(obj, value.replaceAll("\\s", "")
                                .replaceAll("\\n", "")
                                .replaceAll("\\r", "")); // 删除所有空格、回车、换行
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将BigDecimal值*100%转为百分比
     * @param data 输入参数
     * @return xx%
     */
    public static String convertToPercentage(BigDecimal data) {
        // 将输入数字*100%
        String str = data.multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
        return String.format("%s%s", str, "%");
    }
}
